<?php

$currencies = array_index($db->fetchAll("SELECT * FROM shop_currencies"), 'iso');
require $app_root . '/admin/frontend/_modules/shop/includes/modifier.format_price.php';

$order_id = $path[3];

if (ctype_digit($order_id)) {
	
	$order = $db->fetchRow("SELECT o.*, c.title AS billing_country FROM shop_orders o LEFT JOIN cms_countries c ON o.billing_country_id=c.id WHERE site_id=? AND o.id=?", array($site['id'], $order_id));
	list($order['ip_address_country'], $order['ip_address_country_id']) = array_values($db->fetchRow("SELECT country_name, c.id FROM cms_iptoc ip LEFT JOIN cms_countries c ON ip.country_code2=c.iso2 WHERE INET_ATON(?) >= ip_from AND INET_ATON(?) <= ip_to", array($order['ip_address'], $order['ip_address'])));
	$order['transactions'] = $db->fetchAll("SELECT * FROM shop_orders_transactions WHERE order_id=?", $order['id']);
	$order['deliveries'] = array_index($db->fetchAll("SELECT d.*, c.title AS delivery_country FROM shop_orders_deliveries d LEFT JOIN cms_countries c ON d.delivery_country_id=c.id WHERE order_id=?", $order['id']), 'id');
	$order['delivery_price_excl_vat'] = 0;
	$order['delivery_vat']            = 0;
	$order['price_excl_vat']          = 0;
	$order['vat']                     = 0;
	$order['total']                   = 0; 
	foreach($order['deliveries'] as &$delivery) {
		$delivery['lines'] = $db->fetchAll("SELECT * FROM shop_orders_lines WHERE delivery_id=?", $delivery['id']);
		foreach($delivery['lines'] as &$line) {
			$line['simpleattributes'] = $db->fetchAll("SELECT * FROM shop_orders_lines_simpleattributes WHERE line_id=? ORDER BY sort", $line['id']);
			$order['price_excl_vat'] += $line['price_excl_vat'];
			$order['vat']            += $line['vat'];
		}
		$order['delivery_price_excl_vat'] += $delivery['price_excl_vat'];
		$order['delivery_vat'] += $delivery['vat'];
	}
	$order['total'] = $order['price_excl_vat']
	                + $order['vat']
	                + $order['delivery_price_excl_vat']
	                + $order['delivery_vat'];
	
	if (isset($_POST)) {
		
		if (isset($_POST['tracking_reference']) and $_POST['tracking_reference'] != 'Tracking reference' and isset($_POST['delivery_id'])) {
			$db->update('shop_orders_deliveries', array('tracking_reference' => $_POST['tracking_reference']), $db->quoteInto('order_id=?', $order_id) . ' AND ' . $db->quoteInto('id=?', $_POST['delivery_id']));
			$order['deliveries'][$_POST['delivery_id']]['tracking_reference'] = $_POST['tracking_reference'];
		}
		
		if (isset($_POST['status'])) {
			$db->update('shop_orders', array('status' => $_POST['status']), $db->quoteInto('id=?', $order_id) . ' AND ' . $db->quoteInto('site_id=?', $site['id']));
			$order['status'] = $_POST['status'];
			
			if ($_REQUEST['status_message']) {
				$smarty->assign('order', $order);
				$smarty->assign('status_message', $_REQUEST['status_message']);
				$mail = new Zend_Mail('UTF-8');
				if (file_exists("{$app_root}{$site['home_dir']}/templates/shop/emails/status.tpl.text")) $mail->setBodyText($smarty->fetch("{$app_root}{$site['home_dir']}/templates/shop/emails/status.tpl.text"));
				if (file_exists("{$app_root}{$site['home_dir']}/templates/shop/emails/status.tpl.html")) $mail->setBodyHtml($smarty->fetch("{$app_root}{$site['home_dir']}/templates/shop/emails/status.tpl.html"));
				$mail->setFrom($env['shop']['emails']['status']['sender'], $env['shop']['emails']['status']['sender_name']);
				$mail->addTo($order['email'], $order['billing_first_name'] . ' ' . $order['billing_last_name']);
				$mail->setSubject(str_replace("__ORDERID__", $order['id'], $env['shop']['emails']['status']['subject']));
				if (!$mail->send()) {
					$logger->crit("Status update email for order {$order_id} failed.");
				}
			}
			
		}
		
		if (isset($_REQUEST['dispatched'])) {
			if ($db->fetchOne("SELECT id FROM shop_orders WHERE id=? AND site_id=?", array($order_id, $site['id']))) {
				$db->update('shop_orders_deliveries', array('dispatched' => 1), $db->quoteInto('id=?', $_REQUEST['dispatched']));
				$order['deliveries'][$_REQUEST['dispatched']]['dispatched'] = 1;
				if ($db->fetchOne("SELECT COUNT(*) FROM shop_orders_deliveries WHERE order_id=? AND dispatched=0", $order_id) == 0) {
					$db->update('shop_orders', array('status' => 'complete'), $db->quoteInto('id=?', $order_id) . ' AND ' . $db->quoteInto('site_id=?', $site['id']));
					$order['status'] = 'complete';
				}
				$smarty->assign('order', $order);
				$smarty->assign('delivery', $order['deliveries'][$_REQUEST['dispatched']]);
				$mail = new Zend_Mail('UTF-8');
				if (file_exists("{$app_root}{$site['home_dir']}/templates/shop/emails/dispatched.tpl.text")) $mail->setBodyText($smarty->fetch("{$app_root}{$site['home_dir']}/templates/shop/emails/dispatched.tpl.text"));
				if (file_exists("{$app_root}{$site['home_dir']}/templates/shop/emails/dispatched.tpl.html")) $mail->setBodyHtml($smarty->fetch("{$app_root}{$site['home_dir']}/templates/shop/emails/dispatched.tpl.html"));
				$mail->setFrom($env['shop']['emails']['status']['sender'], $env['shop']['emails']['status']['sender_name']);
				$mail->addTo($order['email'], $order['billing_first_name'] . ' ' . $order['billing_last_name']);
				$mail->setSubject(str_replace("__ORDERID__", $order['id'], $env['shop']['emails']['dispatched']['subject']));
				if (!$mail->send()) {
					$logger->crit("Dispatch email for order {$order_id} failed.");
				}
			}
		}
		
	}
	
	
	$smarty->assign('order', $order);
	
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
		header('Content-type: text/xml');
		$smarty->display('shop/orders/_edit.tpl.taconite');
	} else {
		$smarty->display('shop/orders/edit.tpl.html');
	}	
} else {
	$_SESSION['messages'][] = array('title' => 'Error', 'body' => "No order ID was provided.");
	header("Location: /admin/shop/orders/");
}
